<template>
  <div class="page has-serach" >
    <div class="page-content" id="xzrwList">
      <!-- <pub-search
        v-model:searchColumns="state.searchColumns"
        v-model:searchForm="state.searchForm"
        mask-append-to="table-container"
        @search="getPageData"
        :noColumns="true"
        ref="pubSearchRef"
      ></pub-search> -->
      <el-icon class="refresh-icon" :size="30" @click="fetchList"><Refresh /></el-icon>
      <div class="table-container" v-loading="tableLoading">
        <pub-table-auto-height
          ref="pubTable"
          :column="state.columns"
          :data="state.tableData"
          :loading="tableLoading"
          maxHeight="400"
        >
          <template v-slot:fileName="scope">
            <div class="file-name">
              <img
                v-if="scope.row.status != 2"
                src="../../../assets/common/circle.png"
                width="8"
              />
              {{ scope.row.fileName }}
            </div>
          </template>
          <template v-slot:fileLen="scope">
            {{ formatFileSize(scope.row.fileLen) }}
          </template>
          <template v-slot:status="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
          <template v-slot:option="scope">
            <el-button
              v-if="scope.row.status == 1 || scope.row.status == 2"
              class="btn-row-info"
              plain
              type="primary"
              @click.stop="handleDownload(scope.row)"
            >
              下载
            </el-button>
            <el-button
              class="btn-row-info"
              plain
              type="primary"
              @click.stop="handleDel(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </pub-table-auto-height>
      </div>
      <pub-pagination
        :total="total"
        v-model:page="state.searchForm.pageNum"
        v-model:limit="state.searchForm.pageSize"
        @pagination="getPageData"
      />
    </div>
    <div
        v-if="pageDialog"
        title=""
        :show-close="false"
        :modal="true"
        width="100%"
        height="100%"
        center
        :append-to-body="false"
        append-to="axzrwList"
        class="page-dialog"
      >
        删除弹框
      </div>
  </div>
</template>

<script setup>
import { get_list, downLoad, deleteTask } from './api.js'
import { get_xzrw_count } from '@/api/api'
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { Edit, Search, Upload, Plus, Files } from '@element-plus/icons-vue'
import { appCurrentState } from '@/pinia/modules/app.js'
const tableLoading = ref(false)
const total = ref(0)
const state = reactive({
  tableData: [],
  searchForm: {
    pageSize: 15,
    pageNum: 1
  },
  columns: [
    { label: '文件名称', slot: 'fileName' },
    { label: '大小', prop: 'fileLen', width: 100, slot: 'fileLen' },
    { label: '状态', prop: 'status', width: 100, slot: 'status' },
    { label: '操作', type: 'option', width: '180' }
  ]
})
const pubSearchRef = ref(null)
const currentId = ref('')
const pageDialog = ref(false)
// 删除弹框
const del = id => {
  ElMessageBox.confirm('确认删除选择的记录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    appendTo:'#xzrwList'
  })
    .then(async () => {
      let { succeed, msg } = await del_record(id)
      if (succeed) {
        ElMessage.success(msg)
        getPageData()
      }
    })
    .catch(() => {})
}

const fetchList = () => {
  state.searchForm.pageNum = 1
  getPageData()
}
const formatFileSize = fileSize => {
  if (fileSize < 1024) {
    return fileSize + 'B'
  } else if (fileSize < 1024 * 1024) {
    const temp = fileSize / 1024
    return temp.toFixed(2) + 'KB'
  } else if (fileSize < 1024 * 1024 * 1024) {
    const temp = fileSize / (1024 * 1024)
    return temp.toFixed(2) + 'MB'
  } else {
    const temp = fileSize / (1024 * 1024 * 1024)
    return temp.toFixed(2) + 'GB'
  }
}
const formatStatus = status => {
  // ...
  if (status == 1) {
    return '已完成'
  }
  if (status == 2) {
    return '已下载'
  }
  if (status == 3) {
    return '生成失败'
  }
  return '准备中'
}
const getPageData = async () => {
  tableLoading.value = true
  let res = await get_list(state.searchForm)
  if (res.succeed) {
    state.tableData = res.data
    total.value = res.total
  }
  tableLoading.value = false
}
// blob对象转json 判断错误信息
const blobToText = blob => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.readAsText(blob)
    fileReader.onload = function (ev) {
      try {
        const result = JSON.parse(ev.target.result)
        if (result && result.succeed == false) {
          resolve(result)
        } else {
          reject()
        }
      } catch (e) {
        // TODO handle the exception
        reject()
      }
    }
  })
}
const startDownload = (res, fileName) => {
  const blob = new Blob([res], {
    type: res.type
  })
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName)
  } else {
    var link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = fileName
    link.click()
    // 释放内存
    window.URL.revokeObjectURL(link.href)
  }
}
const handleDownload = async row => {
  tableLoading.value = true
  const res = await downLoad(row.id)
  // tableLoading.value = false
  let { data } = await get_xzrw_count()
  appCurrentState().SET_XZRW_COUNT(data)
  if (res instanceof Blob) {
    blobToText(res)
      .then(result => {
        ElMessage.error(result.msg)
      })
      .catch(() => {
        startDownload(res, row.fileName)
        getPageData()
      })
  }
}
const handleDel = id => {
  ElMessageBox.confirm('确认删除选择的记录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    appendTo:'#xzrwList'

  })
    .then(async () => {
      tableLoading.value = true
      let { succeed, msg } = await deleteTask(id)
      let { data } = await get_xzrw_count()
      appCurrentState().SET_XZRW_COUNT(data)
      tableLoading.value = false
      if (succeed) {
        ElMessage.success(msg)
        getPageData()
      }
    })
    .catch(() => {})
}
onMounted(() => {
  getPageData()
})
defineExpose({fetchList})
</script>
<style lang="scss" scoped>
.table-container {
  height: calc(100% - 130px);
  flex: 1;
}
.page-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
}
.h-100p {
  height: 100% !important;
}
.mask-content {
  width: calc(100% + 35px) !important;
  .more-columns-content {
    padding-right: 128px !important;
  }
}

.bottom-btns {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #dcdfe6;
}
.link {
  color: rgb(8, 124, 214);
  cursor: pointer;
  font-weight: bold;
}
:deep(.pub-search) {
  display: none;
}
.file-name {
  display: flex;
  align-items: center;
  img {
    margin-right: 5px;
  }
}
.refresh-icon{
  position:absolute;
  cursor:pointer;
  width: 20px;
  height:20px;
  right:40px;
  top:10px;
}
</style>
